<?php
class VoteAction extends Action {

	//投票详情
	public function showVote() {
		$this->assign('id', intval($_GET['id']));
		$this->display();
	}

	function add() {
		$this->assign('now_year',  date('Y'));
		$this->assign('now_month', date('m'));
		$this->assign('now_day',   date('d'));
		
		$type = isset($_GET['type']) ? 2 : 1; //1:页面加载 2:AJAX加载
		$this->assign('type', $type);
		$this->display();
	}
	
	//发起投票
	public function doAddVote() {
		if(isset($_POST['isAjax']) && intval($_POST['isAjax']) == 1) {
			$return_type = 'ajax';
		}else {
			$return_type = 'return';
		}

		$_POST['title'] = t($_POST['title']);

		//检验数据合法性
		if(empty($_POST['title']) || empty($_POST['opt']) || !is_numeric($_POST['type']) || count($_POST['opt']) < intval($_POST['type']) - 1) {
			if($return_type == 'return') {
				$this->error( '参数不合法' );
			}else if($return_type == 'ajax') {
				echo 0;
				return ;
			}
		}
		if($_POST['deadline_type'] == 'u') {
			if(!is_numeric($_POST['month']) || !is_numeric($_POST['day']) || !is_numeric($_POST['year'])) {
				if($return_type == 'return') {
					$this->error( '结束日期的参数不合法' );
				}else if($return_type == 'ajax') {
					echo 0;
					return ;
				}
			}
			$deadline = mktime(0,0,0,intval($_POST["month"]),intval($_POST["day"]),intval($_POST["year"]));
		}else {
			if(!is_numeric($_POST['deadline_type'])) {
				if($return_type == 'return') {
					$this->error( '结束日期的参数不合法' );
				}else if($return_type == 'ajax') {
					echo 0;
					return ;
				}
			}
			$deadline = mktime(0,0,0,date('m'),date('d') + intval($_POST['deadline_type']),date('Y'));
		}

		if($deadline < time()) {
			if($return_type == 'return') {
				$this->error("投票的截止时间不能早于发起投票的时间！");
			}else if($return_type == 'ajax') {
				echo -1;
				return ;
			}
		}

		//检测选项是否重复
		$opt_test = array_filter($_POST['opt']);
		$opt_test_count = count(array_unique( $opt_test ));
		if( $opt_test_count < count($opt_test) ) {
			if($return_type == 'return') {
				$this->error( '投票不允许有重复项' );
			}else if($return_type == 'ajax') {
				echo -2;
				return ;
			}
		}

		//投票表
		$voteDao  = M('vote');
		$voteUser = M('vote_user');

		$voteDao->create();
		$voteDao->uid      = $this->mid;
		$voteDao->deadline = $deadline;
		$voteDao->name     = $this->user['fullname'];
		$voteDao->cTime    = time();
		$vote_id = $voteDao->add();

		$voteUser->create();
		$voteUser->uid      = $this->mid;
		$voteUser->name     = $this->user['fullname'];
		$voteUser->vote_id  = $vote_id;
		$voteUser->cTime    = time();
		$voteUser->add();

		//选项表
		$feed = array();
		$optDao = M('vote_opt');
		foreach($_POST["opt"] as $v) {
			if(!$v) continue;
			$data["vote_id"] = $vote_id;
			$data["name"]    = t($v);
			$optDao->add($data);
		}

		if($return_type == 'return') {
			$this->assign('jumpUrl', U('home/Vote/detail', 'id=' . $vote_id));
			$this->success('投票成功～');
		}else if($return_type == 'ajax') {
			echo $vote_id;
		}
	}

	//投票详情
	public function detail() {
		$id = intval($_GET["id"]);
		if( empty( $id ) || 0 == $id ) {
			$this->error( "非法访问投票页面" );
		}

		//投票详情
		$vote = M('vote')->find($id);
		if( false == $vote ) {
			$this->error('浏览的投票不存在或者被删除');
		}
		$this->assign('vote', $vote);

		//投票选项
		$vote_opts = M('vote_opt')->where('vote_id = ' . $id)->order('id ASC')->findAll();
		$this->assign('vote_opts', $vote_opts);

		//投票的参与者
		$vote_users = M('vote_user')->where("vote_id = $id AND opts <> '' ")->findAll();

		//检查是否已投票
		if(!isset($vote_users)) {
			$has_vote = false;
		}else {
			$uids = formatArray($vote_users, 'uid');
			$has_vote = in_array($this->mid, $uids) ? true : false;
		}

		$this->assign( 'has_vote', $has_vote );
		$this->assign( 'vote_users', $vote_users);

		//投票的百分比
		foreach($vote_opts as $v) {
			$nums[] = (int)($v['num']);
			$total += (int)($v['num']);
		}
		foreach($nums as $v) {
			$pers[] = round(((float)$v/(float)$total)*100,0);
		}
		$this->assign('vote_pers',$pers);

		$this->display();
	}

	//投票列表
	public function votelist($map = array(), $order = 'cTime DESC', $limit = 10) {
		$votes = M('vote')->where($map)->order($order)->findPage($limit);

		//选项
		$model = M('vote_opt');
		foreach($votes['data'] as $k=>$v) {
			$opts = $model->where("vote_id = {$v['id']}")->order("id ASC")->field("*")->limit('0,2')->findAll();
			$votes['data'][$k]['opts'] = $opts;
		}

		$this->assign($votes);
		$this->display();
	}

	//ajax获取投票详情
	public function getVotesDetail() {
		$ids  = isset($_POST['ids']) ? explode(',', $_POST['ids']) : array('0');
		$list = array();

		$map['id'] = array('in', $ids);
		$list = M('vote')->where($map)->order('id DESC')->findAll();

		$opt_dao  = M('vote_opt');
		$user_dao = M('vote_user');
		foreach($list as $k => $v) {
			//投票的选项
			$list[$k]['opt']  = $opt_dao->where('vote_id=' . $v['id'])->order('id ASC')->findAll();
			
			//参与投票的用户
			$list[$k]['user'] = $user_dao->where('vote_id=' . $v['id'] . ' AND opts <> "" ')->order('id DESC')->limit(5)->findAll();
			
			//是否已投票
			if(!isset($list[$k]['user'])) {
				$list[$k]['has_vote'] = false;
			}else {
				$uids = formatArray($list[$k]['user'], 'uid');
				$list[$k]['has_vote'] = in_array($this->mid, $uids) ? true : false;
			}
			
			//各选项的百分比
			foreach($list[$k]['opt'] as $v2) {
				$nums[] = (int)($v2['num']);
				$total += (int)($v2['num']);
			}
			foreach($nums as $v2) {
				$per[] = round(((float)$v2/(float)$total)*100,0);
			}
			$list[$k]['per'] = $per;
			unset($per);
			unset($nums);
			unset($total);
		}

		//组装html代码
		$votes = '';
		$i = 0;
		foreach($list as $v) {
			$votes[$v['id']] = '<div id="vote_' . $v['id'] . '" class="LogList"><ul><li>';

			//用户信息
			$votes[$v['id']] .= '
			  <div class="c1"> 
				<span class="headpic50"> <a href="#" class="tips" rel="#" target="_blank"><img src="' . getUserFace($v['uid']) . '" /></a> </span> 
				<a href="#" class="U" target="_blank">' . $v['name'] . '</a> 
			  </div>';
			
			//投票信息
			$votes[$v['id']] .= '
			  <div class="c2 cl06">
				<p>发起时间：' . date('Y-m-d H:i:s', $v['cTime']) . '</p>
				<p id="vote_' . $v['id'] . '_num">已投票数：' . $v['vote_num'] . '</p>
				<p id="vote_deadline_2">结束时间：' . date('Y-m-d H:i:s', $v['deadline']) . '</p>
			  </div>
			';

			//管理信息
			if($v['uid'] == $this->mid) {
				$votes[$v['id']] .= '
				  <div class="c3">
					<a href="javascript:vote_admin(' . $v['id'] . ',1)">增加选项</a><br />
				';

				if($votes[$v['deadline']] < time()) {
					$votes[$v['id']] .= '
						<a href="javascript:vote_admin(' . $v['id'] . ',2)">修改结束时间</a><br />
					';
				}else {
					$votes[$v['id']] .= '
						投票已结束<br />
					';
				}
				$getURL=U('home/Vote/outExcel&id='.$v['id']);
				$votes[$v['id']] .= '
					<a href="'.$getURL.'">导出投票</a><br />
				';
				$votes[$v['id']] .= '
				  </div>
				';
				
				//$votes[$v['id']] .= '
				//	<a href="javascript:vote_admin(' . $v['id'] . ',3)">删除投票</a><br />
				//  </div>
				//';
			}

			$votes[$v['id']] .= '<div class="C"></div>';
			$max = intval($v['type']) + 1;
			$votes[$v['id']] .= '
				<div style="width: 70%; margin: 0pt auto;">
                  <h1 class="alC lh35 f14"><span class="f14 fB">' . $v['title'] . '</span><span class="cl06">(可选<span id="most_vote_num">' . $max . '</span>个)</span></h1>
                  <p class="cl06">' . $v['explain'] . '</p>
                </div>
			';

			$votes[$v['id']] .= '
			  <div class="LogList" style="width:100%; ">
			';

			$votes[$v['id']] .= '
				
				    <ul style="width:570px;" class="left" id="vote_' . $v['id'] . '_opt">
			';

			//选项信息
			$form_type = ($v['type'] == 0) ? 'radio' : 'checkbox';
			foreach($v['opt'] as $k => $opt) {
				$index = $k + 1;
				$votes[$v['id']] .= '
				  <li>
					<div class="left lh25" style="margin-left:20px; width:20px;">' . $index . '. </div>
					<div class="alL left lh25 " style="width: 80%;">' . $opt['name'] . ': </div>
					<div class="left" style="width: 204px;margin-left: 30px;_margin-left: 25px;">
					  <div class="poll">
						<div class="vbg v1 vote-per-' . $k . '" id="vote_' . $v['id'] . '_opt_' . $k . '_per" style="width:0px;"> <span></span> </div>
					  </div>
					</div>
					<div class="left" id="vote_' . $v['id'] . '_opt_' . $k . '_static" style="width: 81px;">' . $opt['num'] . ' / ' . $v['per'][$k] . '%</div>
				';
				if($v['has_vote'] === false) {
					$votes[$v['id']] .= '
						<div class="left vote_' . $v['id'] . '_check" style="width: 30px;">
						  <input name="vote_opt" type="' . $form_type . '" value="' .$opt['name'] . '" id="' .$opt['id'] . '"/>
						</div>
					';
				}
				$votes[$v['id']] .= '
					<div class="C"></div>
				  </li>
				';
			}

			$votes[$v['id']] .= '
				    </ul>
				
			';

			//底部
			if($v['has_vote'] === false) {
				$max = $v['type'] + 1;
				$votes[$v['id']] .= '
				  <div class="C"></div>
					<div style="padding-left:230px; margin:10px 0;"> 
						<input name="" type="button" class="btn_sea mr10" value="投票" href="javascript:void(0)" onclick="post_vote(' . $v['id'] . ',' . $max . ')"/>
						<input name="" type="button"  value="收起" class="btn_sea" href="javascript:void(0)" onclick="hide_vote_detail(' . $v['id'] . ')"/>
					</div>
				  </div>
				';
			}else {
				$votes[$v['id']] .= '
				  <div class="C"></div>
					<div style="padding-left:130px; margin:10px 0;"> 
						<input name="" type="button" class="btn_sea mr10" value="您已投票" disabled="true"/>
						<input name="" type="button"  value="收起" class="btn_sea" href="javascript:void(0)" onclick="hide_vote_detail(' . $v['id'] . ')"/>
					</div>
				  </div>
				';
			}
			$votes[$v['id']] .= '</li></ul></div>';

			//参与投票的用户
			if($v['is_anonymous'] == 0) {
				$votes[$v['id']] .= '
					<div style="padding-bottom: 20px;" class="circs" id="circs_vote_' . $v['id'] . '">
					  <dl>
						<dt><a class="R" href="javascript:void(0)" id="vote_show_hide_users" onclick="vote_show_hide_users('.$v['id'].');">收起</a>大家的投票情况：</dt>
						<div class="vote_opts" style="display: block;">
						  <dd id="vote_' . $v['id'] . '_user">
				';

				if(empty($v['user'])) {
					$votes[$v['id']] .= '<div style="width: 580px;" class="left">暂无投票</div>';
				}else {
					foreach($v['user'] as $user) {
						if($user['uid'] == $this->mid) {
							$votes[$v['id']] .= '
									<div style="width: 20px;" class="left mt5"><img src="'.__THEME__.'/images/arrow_y.gif"/> </div>
							';
						}else {
							$votes[$v['id']] .= '
									<div style="width: 20px;" class="left mt5"> </div>
							';
						}

						$votes[$v['id']] .= '
									<div style="width: 580px;" class="left"><a href="' . U('space/View/index',array('uid'=>$user['uid'])) . '" target="_blank">' . $user['name'] . '</a> ' . friendlyDate($user['cTime']) . '  投票给“' . $user['opts'] . '”</div><div class="C"></div>
						';
					}
					$limit_b = 5; //起始位置
					$limit_e = 5; //显示数量
					//查看更多投票用户
					$votes[$v['id']] .= '
						<div style="width: 580px;" class="left" id="vote_'.$v['id'].'_more_users">
							<div style="width: 20px;" class="left mt5"> </div>
							<a href="javascript:void(0)" onclick="updateUsers('.$v['id'].','.$limit_b.','.$limit_e.')">[更多]</a>
						</div>
					';
				}
				
				$votes[$v['id']] .= '
						  </dd>
						</div>
					  </dl>
					  <div class="c"></div>
					</div>
				';
			}else {
				$votes[$v['id']] .= '
					<div style="padding-bottom: 20px;" class="circs" id="circs_vote_' . $v['id'] . '" onclick="$(\'.vote_opts\').slideToggle(\'slow\');">
					  <dl>
						<dt>本投票为匿名投票</dt>
					  </dl>
					  <div class="c"></div>
					</div>
				';
			}

			$i++;
		}

		echo json_encode($votes);
	}

	//ajax获取投票各选项的百分比
	public function getOptPercent() {
		if(!isset($_POST['id'])) {
			echo 0;
			return ;
		}
		$id  = intval($_POST['id']);
		$opts = M('vote_opt')->where('vote_id=' . $id)->order('id ASC')->findAll();
		foreach($opts as $v) {
			$nums[] = (int)($v['num']);
			$total += (int)($v['num']);
		}
		foreach($nums as $v) {
			$pers[] = $v . ';' . round(((float)$v/(float)$total)*100,0);
		}
		
		//投票人数
		$num_of_users = M('vote_user')->where('vote_id=' . $id . ' AND opts <> ""')->field('uid')->count();
		$pers['num_of_users'] = $num_of_users;
		echo json_encode($pers);
	}

	//ajax获取参与投票的用户
	public function getVoteUsers() {
		if(!isset($_POST['id'])) {
			echo 0;
			return;
		}
		$id      = intval($_POST['id']);
		$limit_b = isset($_POST['limit_b']) ? intval($_POST['limit_b']) : 0;
		$limit_e = isset($_POST['limit_e']) ? intval($_POST['limit_e']) : 5;
		$limit   = $limit_b . ',' . $limit_e;

		$is_anonymous = M('vote')->where('id='.$id.' AND is_anonymous = 1')->limit(1)->findAll();
		if($is_anonymous) {
			echo 'is_anonymous';
			return ;
		}
		$users = M('vote_user')->where('vote_id='.$id.' AND opts<>""')->limit($limit)->order('id DESC')->findAll();

		//格式化时间格式
		foreach($users as $k => $v) {
			$users[$k]['cTime'] = friendlyDate($v['cTime']);
		}

		echo json_encode($users);
	}

	//投票
	public function postVote() {
		//用户投票信息
		$voteUserDao = M('vote_user');

		//先看看有无权限投
		$vote_id = intval($_POST["vote_id"]);
		//检查ID是否合法
		if( empty($vote_id) || 0 == $vote_id ) {
			$this->error( "错误的投票ID" );
		}

		$voteDao      = M('vote');
		$the_vote     = $voteDao->where("id=$vote_id")->find();
		$onlyfriend   = $the_vote['onlyfriend'];
		$vote_user_id = $the_vote['uid'];
		$deadline     = $the_vote['deadline'];
		if( $deadline <= time() ) {
			echo -2;
			return;
		}

		//再看看投过没
		$vote_id = intval($_POST["vote_id"]);
		$count = $voteUserDao->where( "vote_id=$vote_id AND uid=" . $this->mid . " AND opts <>''" )->count();
		if($count > 0) {
			echo -1;
			return;
		}

		//如果没投过，就添加
		$data["vote_id"] = $vote_id;
		$data["uid"]     = $this->mid;
		$data["opts"]    = rtrim(t($_POST["opts"]),",");
		$data["cTime"]   = time();
		$data['name']    = $this->user['fullname'];
		$addid = $voteUserDao->add($data);

		//投票选项信息的num+1
		$dao = M("vote_opt");

		$opts_ids = rtrim(t($_POST["opts_ids"]),",");
		$opts_ids = explode(",",$opts_ids);

		foreach($opts_ids as $v) {
			$v = intval($v);
			$dao->setInc("num","id=$v");
		}

		//投票信息的vote_num+1
		M("vote")->setInc("vote_num","id=$vote_id");

		//动态

		//积分

		echo 1;
	}

	//删除投票
	public function delVote() {
		echo 0;
		return ;
		if(!isset($_POST['id'])) {
			echo 0;
			return ;
		}
		$id  = intval($_POST['id']);
		$res = M('vote')->where('id='.$id)->delete();
		$res = $res && M('vote_opt')->where('vote_id='.$id)->delete();
		M('vote_user')->where('vote_id='.$id)->delete();
		if($res) {
			echo 1;
		}else {
			echo 0;
		}
	}

	//编辑投票
	public function doAddOpt() {
		if(!isset($_POST['id']) || !isset($_POST['title'])) {
			echo 0;
			return ;
		}
		$id    = intval($_POST['id']);
		$title = t($_POST['title']);

		//判断是否重名
		$res = M('vote_opt')->where('vote_id=' . $id . ' AND name="' . $title . '"')->limit(1)->findAll();
		if($res) {
			echo -1; //有重名的
			return ;
		}

		//添加选项
		$data['vote_id'] = intval($_POST['id']);
		$data['name']    = t($_POST['title']);
		$res = M('vote_opt')->add($data);
		if(!$res) {
			echo 0;
			return ;
		}

		//返回新增选项在投票中的位置（从0开始）,选项ID,投票的类型,是否已投票
		$count = M('vote_opt')->where('vote_id=' . $id)->count();
		$type  = M('vote')->where('id='.$id)->field('type')->limit(1)->findAll();
		$type  = $type[0]['type'];
		$has_v = M('vote_user')->where('vote_id = '. $id . ' AND opts <> "" AND uid = ' . $this->mid)->limit(1)->findAll();
		if($has_v) {
			$has_v = 1;
		}else {
			$has_v = 0;
		}
		echo $count - 1 . ',' . $res . ',' . $type . ',' . $has_v;
	}

	//更新截止时间
	public function doUpdateDeadline() {
		if(!isset($_POST['id']) || !isset($_POST['type'])) {
			echo 0;
			return;
		}
		$id = intval($_POST['id']);
		if(t($_POST['type']) == 'u') {
			$deadline = mktime(0,0,0,$_POST["month"],$_POST["day"],$_POST["year"]);
		}else {
			$deadline = mktime(0,0,0,date('m'),date('d') + intval($_POST['type']),date('Y'));
		}
		//检验有效性
		if($deadline < time()) {
			echo -1; //投票截止时间不能早于当前
			return ;
		}
		$res = M('vote')->where('id='.$id)->setField('deadline', $deadline);
		if($res) {
			echo date('Y-m-d H:i:s', $deadline);
		}else {
			echo 0;
		}
	}
	
	function outExcel(){
		$voteDao  = M('vote');		
		$optDao   = M('vote_opt');
		$voteUser = M('vote_user');	
		
		$ids = $_REQUEST['id'];
		$ids = explode(',', $ids);
		foreach ($ids as $v){
			$id = intval($v);
			if(empty($id)) continue;
			
			$vote = $voteDao->where("id='$id'")->find();
			if(empty($vote)) continue;
			
			$vote['type']     = $vote['type']>0 ? '多选' : '单选';
						
			$list = $optDao->where("vote_id='$id'")->field('name,num')->findall();
			foreach ($list as $vo){
				$vote['num'] += $vo['num'];
			}			
			foreach ($list as $vo){
				$vo['per'] = number_format(($vo['num']/$vote['num'])*100, 2)."%";
				$vote['opt'][] = $vo;
			}
			
			$list = $voteUser->where("vote_id='$id' AND opts<>''")->field('name,opts,cTime')->findall();
			foreach ($list as $vo){
				$vote['user'][] = $vo;
			}	

			$vote = $this->_ExcelTemp($vote);
			
			if(empty($dataArr)){
				$dataArr = $vote;
			}else{
				$dataArr = array_merge($dataArr, $vote);
			}
		}		

		require ADDON_PATH.'/libs/phpExcel/php-excel.class.php';	
		
		$xls = new Excel_XML('UTF-8');
		$xls->addArray($dataArr);
		$xls->generateXML("vote_".date('Y-m-d'));		
	}
	
	function _ExcelTemp($vo){		
		$res = array(
		   1 => array ('标题：',    $vo['title']),
		   2 => array ('说明：',    $vo['explain']),
		   3 => array ('开始时间：', date("Y-m-d H:i:s", $vo['cTime'])),
		   4 => array ('结束时间：', date("Y-m-d H:i:s", $vo['deadline'])),
		   5 => array ('总投票数：', $vo['num']),
		   6 => array ('类型：',     $vo['type']),
		   7 => array ('选项：'),		   
		);
		
		$i=8;		
		foreach ($vo['opt'] as $k=>$v){			
			$res[$i] = array('', $v['name'], $v['num'], $v['per']);
			$i++;
		}
		
		$res[$i] = array('投票情况：');
		foreach ($vo['user'] as $k=>$v){
			$i++;
			$res[$i] = array('', $v['name'], $v['opts'], date("Y-m-d", $vo['cTime']));
		}

		$res[$i+1] = array();

		return $res;
	}
}
?>